<script setup lang="ts">
import { addPropertyAPI, deletePropertyAPI, getBuildingDataAPI, getEnterpriseDataAPI, getPaymentAPI, getPropertyAPI } from '@/apis/property';
import type { PropertyType, GetPropertyParamsType, EnterpriseType, AddPropertyParams, buildingType } from '@/types/property';
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus';
import { ref, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';

// 请求列表参数
const getPropertyParams = ref<GetPropertyParamsType>({
  page: 1,
  pageSize: 5,
  enterpriseName: '',
  start: undefined,
  end: undefined
})

// 计算日期
const dateComputed = ref<string[] | undefined>()
watch(dateComputed, (newValue) => {
  if (newValue) {
    getPropertyParams.value.start = newValue[0]
    getPropertyParams.value.end = newValue[1]
  } else {
    getPropertyParams.value.start = undefined
    getPropertyParams.value.end = undefined
  }
})

// 请求列表数据
const propertyList = ref<PropertyType[]>([])
const totalProperty = ref<number>(0)

const getPropertyData = async () => {
  const res = await getPropertyAPI(getPropertyParams.value)
  console.log(res)
  propertyList.value = res.data.rows
  totalProperty.value = res.data.total
}
getPropertyData()

// 添加弹窗
const addDialogVisible = ref(false) // 添加弹窗控制
const addFormRef = ref<FormInstance>()
// 开启添加弹窗
const openAddDialog = () => {
  addDialogVisible.value = true

  getEnterpriseData() // 获取企业数据
  getBuildingData() // 获取楼宇数据
}

const router = useRouter()
// 关闭添加弹窗
const closeAddDialog = () => {
  addFormRef.value?.resetFields() // 重置表单
  dateDaterange.value = undefined // 重置日期

  if (route.query.type === 'add') {
    router.back()
  }
}
// 手动关闭添加弹窗
const closeManualDialog = () => {
  addDialogVisible.value = false
}

// 获取企业数据
const enterpriseList = ref<EnterpriseType[]>([])
const getEnterpriseData = async () => {
  const res = await getEnterpriseDataAPI()
  enterpriseList.value = res.data
}

// 获取楼宇数据
const buildingList = ref<buildingType[]>([])
const getBuildingData = async () => {
  const res = await getBuildingDataAPI()
  buildingList.value = res.data
}

// 操作日期
const dateDaterange = ref<string[] | undefined>([])
watch(dateDaterange, (newVal) => {
  if (newVal) {
    addParams.value.startTime = newVal[0]
    addParams.value.endTime = newVal[1]
  } else {
    addParams.value.startTime = undefined
    addParams.value.endTime = undefined
  }
})

// 支付方式
const paymentMethod = [
  { id: 1 ,name: '微信' },
  { id: 2 ,name: '支付宝' },
  { id: 3 ,name: '现金' }
]

// 计算预算金额
const getPaymentAmount = async () => {
  if (addParams.value.startTime && addParams.value.endTime && addParams.value.buildingId) {
    const res = await getPaymentAPI({
      buildingId: addParams.value.buildingId,
      startTime: addParams.value.startTime,
      endTime: addParams.value.endTime
    })
    addParams.value.paymentAmount = +res.data
  } else {
    addParams.value.paymentAmount = undefined
  }
}

// 添加弹窗表单数据
const addParams = ref<AddPropertyParams>({
  buildingId: undefined, // 楼宇id
  endTime: undefined, // 缴费周期-结束时间
  enterpriseId: undefined, // 企业id
  paymentAmount: undefined, // 付款总额
  paymentMethod: 1, // 付款方式1微信2支付宝3现金
  startTime: undefined // 缴费周期-开始时间
})
// 监听预算金额所需要的值 计算金额
watch([() => addParams.value.buildingId, () => addParams.value.startTime, () => addParams.value.endTime], () => {
  getPaymentAmount()
})

// 添加表单规则
const addRules = ref<FormRules<AddPropertyParams>>({
  buildingId: [
    { required: true, message: '请选择楼宇', trigger: 'change' }
  ],
  endTime: [
    { required: true, message: '请选择缴费周期-结束时间', trigger: 'blur' }
  ],
  enterpriseId: [
    { required: true, message: '请选择租户', trigger: 'change' }
  ],
  paymentMethod: [
    { required: true, message: '请选择付款方式', trigger: 'change' }
  ]
})

// 添加物业费-确认
const loadingFlag = ref(false)
const addPropertyConfirm = async () => {
  await addFormRef.value?.validate()

  loadingFlag.value = true

  try {
    await addPropertyAPI(addParams.value)
    ElMessage.success('添加成功')
  } finally {
    loadingFlag.value = false
  }

  getPropertyData()
  closeManualDialog()
}

// 查看弹窗
const showDialogVisible = ref(false) // 弹窗显示隐藏
// 开启弹窗
const openShowDialog = (row: PropertyType) => {
  showDialogVisible.value = true
  // 存储数据
  showDialogData.value = row
}
// 关闭弹窗
const closeShowDialog = () => {
  showDialogVisible.value = false
  // 清空数据
  showDialogData.value = {} as PropertyType
}

// 查看弹窗数据
const showDialogData = ref<PropertyType>({} as PropertyType)

// 支付方式
const methodMap = new Map([
  [1, '微信'],
  [2, '支付宝'],
  [3, '现金']
])

// 删除账单
const deleteProperty = async (id: number) => {
  await ElMessageBox.confirm('确定删除该账单吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
  const res = await deletePropertyAPI(id)
  if(res.code === 10000) {
    ElMessage.success('删除成功')
  } else {
    ElMessage.error(res.msg)
  }
  getPropertyData()
}

const route = useRoute()

if (route.query.type === 'add') {
  openAddDialog()
}

</script>

<template>
  <div class="building-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <div class="search-label">企业名称：</div>
      <el-input @clear="getPropertyData()" v-model="getPropertyParams.enterpriseName" clearable placeholder="请输入内容" class="search-main" />
      <div class="search-label" style="margin-left: 20px;">缴费时间：</div>
      <div class="search-main" style="width: 350px; display: flex;">
        <el-date-picker
          v-model="dateComputed" 
          type="daterange" 
          range-separator="至" 
          start-placeholder="开始日期"
          end-placeholder="结束日期" 
          value-format="YYYY-MM-DD"
        />
        <el-button type="primary" style="width: 15%; margin-left: 20px;" @click="getPropertyData()">查询</el-button>

      </div>
    </div>
    <div class="create-container">
      <el-button type="primary" @click="openAddDialog()" v-permission="'park:propertyFee:add'">添加账单</el-button>
    </div>
    <!-- 表格区域 -->
    <div class="table">
      <el-table style="width: 100%" :data="propertyList">
        <el-table-column type="index" label="序号" width="80" />
        <el-table-column label="账单编号" prop="billNumber" width="180" />
        <el-table-column label="企业名称" prop="enterpriseName" width="180" />
        <el-table-column label="租赁楼宇" prop="buildingName" />
        <el-table-column label="物业费(元/m²)" prop="propertyFeePrice" />
        <el-table-column label="账单金额(元)" prop="paymentAmount" />
        <el-table-column label="缴费时间" prop="createTime" width="200" />
        <el-table-column label="操作">
          <template #default="scope">
            <el-button size="small" type="primary" link @click="openShowDialog(scope.row)" v-permission="'park:propertyFee:query'">查看</el-button>
            <el-button size="small" type="primary" link @click="deleteProperty(scope.row.id)" v-permission="'park:propertyFee:remove'">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页器 -->
    <div class="page-container">
      <el-pagination 
        layout="total, sizes, prev, pager, next"
        :page-sizes="[2,5,10,20]"
        :total="totalProperty" 
        v-model:current-page="getPropertyParams.page" 
        v-model:page-size="getPropertyParams.pageSize"
        @change="getPropertyData()"
      />
    </div>
    <!-- 添加账单 -->
    <el-dialog @close="closeAddDialog()" title="添加账单" width="580px" v-model="addDialogVisible">
      <div class="form-container">
        <!-- 表单区域 -->
        <el-form ref="addFormRef" label-position="top" :model="addParams" :rules="addRules">
          <el-form-item label="选择租户" prop="enterpriseId">
            <el-select placeholder="请选择租户" v-model="addParams.enterpriseId" clearable>
              <el-option
                v-for="item in enterpriseList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="租赁楼宇" prop="buildingId">
            <el-select placeholder="请选择租赁楼宇" v-model="addParams.buildingId" clearable>
              <el-option
                v-for="item in buildingList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="缴费周期" prop="endTime">
            <el-date-picker
              type="daterange" 
              range-separator="➡" 
              start-placeholder="开始日期"
              end-placeholder="结束日期" 
              value-format="YYYY-MM-DD"
              v-model="dateDaterange"
            />
          </el-form-item>
          <el-form-item label="支付金额" prop="paymentAmount">
            <el-input placeholder="请输入支付金额" disabled :value="addParams.paymentAmount"></el-input>
          </el-form-item>
          <el-form-item label="支付方式" prop="paymentMethod">
            <el-select placeholder="请选择支付方式" v-model="addParams.paymentMethod">
              <el-option
                v-for="item in paymentMethod"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button @click="closeManualDialog()">取 消</el-button>
        <el-button type="primary" @click="addPropertyConfirm()" :loading="loadingFlag">确 定</el-button>
      </template>
    </el-dialog>
    <!-- 查看账单 -->
    <el-dialog @close="closeShowDialog()" title="查看账单" width="580px" v-model="showDialogVisible">
      <div class="form-container">
        <!-- 内容区域 -->
        <div class="show-content">
          <div class="show-item"><span class="left">租户名称：</span><span class="right">{{ showDialogData.enterpriseName }}</span></div>
          <div class="show-item"><span class="left">租赁楼宇：</span><span class="right">{{ showDialogData.buildingName }}</span></div>
          <div class="show-item"><span class="left">缴费周期：</span><span class="right">{{ showDialogData.startTime }}至{{ showDialogData.endTime }}</span></div>
          <div class="show-item"><span class="left">物业费(元/m²)：</span><span class="right">{{ showDialogData.propertyFeePrice }}</span></div>
          <div class="show-item"><span class="left">账单金额(元)：</span><span class="right">{{ showDialogData.paymentAmount }}</span></div>
          <div class="show-item"><span class="left">支付方式：</span><span class="right">{{ methodMap.get(+showDialogData.paymentMethod!) }}</span></div>
          <div class="show-item"><span class="left">缴费时间：</span><span class="right">{{ showDialogData.createTime }}</span></div>
        </div>
      </div>
      <template #footer>
        <el-button @click="closeShowDialog()">取 消</el-button>
        <el-button type="primary" @click="closeShowDialog()">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.show-content {
  padding: 30px 0;
  display: flex;
  flex-direction: column;
  gap: 20px;
  .left {
    display: inline-block;
    width: 130px;
    text-align: right;
    color: #909399;
  }
  .right {
    color: #262626;
  }
}

.son-table {
  // background-color: #f4f6f8;
  margin-left: 47px;
}
.building-container {
  padding: 20px;
}

.search-container {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237, 237, 237, .9);
  ;
  padding-bottom: 20px;

  .search-label {
    width: 100px;
  }

  .search-main {
    width: 220px;
    margin-right: 10px;
  }
}

.create-container {
  margin: 10px 0px;
}

.page-container {
  padding: 4px 0px;
  text-align: right;
}

.form-container {
  padding: 0px 80px;
}
</style>
